package net.xdclass.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.config.AlipayConfig;
import net.xdclass.enums.ProductOrderPayTypeEnum;
import net.xdclass.service.ProductOrderService;
import net.xdclass.until.CommonUtil;
import net.xdclass.until.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
@Api("订单回调通知模块")
@Controller
@RequestMapping("/api/callback/v1")
public class CallbackController {

    @Autowired
    private ProductOrderService productOrderService;


    /**
     * 支付回调
     *
     * @param requestre
     * @param response
     * @return
     */
    @PostMapping("alipay")
    public String alipayCallback(HttpServletRequest requestre, HttpServletResponse response) {
        Map<String, String> paramsToMap = CommonUtil.convertRequestParamsToMap(requestre);
        log.info("支付宝回调通知结果:{}", paramsToMap);
        try {
            boolean b = AlipaySignature.rsaCheckV1(paramsToMap, AlipayConfig.ALIPAY_PUB_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGN_TYPE);
            if (b) {
                JsonData jsonData = productOrderService.handlerOrderCallbackMsg(ProductOrderPayTypeEnum.ALIPAY, paramsToMap);
                if (jsonData.getCode() == 0) {
                    return "success";
                }
            }
        } catch (AlipayApiException e) {
            log.error("支付宝回调验签异常:{},参数:{}", e, paramsToMap);
        }
        return "failure";
    }

}
